package com.algorithm.ch1.yjx.string;

/**
 * @author yuanjianxin
 * @date 2018/8/15 16:50
 */
public class ReverseInteger {

    public static void main(String[] args) {
        int num = 123;
        System.out.println(reverse1(num));

    }

    //数组反转的思想
    public static int reverse(int num) {
        char[] chars = (num + "").toCharArray();
        int start = 0;
        if (chars[0] == '-') {
            start++;
        }
        int end = chars.length - 1;
        char temp;
        while (start < end) {
            temp = chars[end];
            chars[end] = chars[start];
            chars[start] = temp;
            start++;
            end--;
        }

        Double ret = new Double(new String(chars));
        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
            return 0;
        }
        return ret.intValue();
    }

    //求余数，比较好的方法
    public static int reverse1(int num) {
        boolean positive = true;
        if (num < 0) {
            positive = false;
            num *= -1;
        }

        double ret = 0;
        while (num > 0) {
            ret = ret * 10 + num % 10;
            num /= 10;
        }

        if (!positive) {
            ret *= -1;
        }

        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
            return 0;
        }

        return (int) ret;
    }
}
